<template>
  <div class="com_attentionPro">
    <van-tabs v-model="activeTabIndex" type="card">
      <van-tab :title="`${whichType == 2 ? '上游' : '下游'}公司`">
        <div v-for="(item, index) in companyListData">
          <com-my-attention :data-item="item" :no-folltime="true" :can-not-go-company="true" :key="item.id">
            <div style="margin-top: 10px; text-align: left" class="concern_item">
              <span>申请时间：</span>
              <span>{{ item.create_time ? item.create_time : '无' }}</span>
            </div>
            <div style="margin-top: 10px; text-align: left; display: flex; align-items:center;" class="concern_item">
              <template v-if="item.audit === 1">
                <span>{{ '已授权时间：' }}</span>
                <span>{{ item.auditdate ? item.auditdate : '' }}</span>
              </template>
              <template v-else-if="item.audit === 2">
                <span>{{ '不授权时间：' }}</span>
                <span>{{ item.auditdate ? item.auditdate : '' }}</span>
              </template>
              <span v-else>授权状态：暂未授权</span>
            </div>

            <div style="margin-top: 10px; text-align: center;" class="concern_item">
              <van-button
                :color="whichType == 2 ? '#1989FA' : '#7232DD'"
                size="small"
                block
                round
                @click.stop="toViewShareJob(whichType, item)"
              >
                {{ `点击查看${whichType == 2 ? '已转发上游公司的招聘信息' : '下游公司已转发的招聘信息'}` }}
              </van-button>
            </div>
          </com-my-attention>
        </div>
      </van-tab>
      <van-tab title="转发后招聘信息" v-if="Object.keys(selectedCompanyObj).length > 0">
        <div v-if="needJobsList.length">
          <job-item-for-recruit
            v-for="(item, index) in needJobsList"
            :key="item.id"
            :jobItem="item"
            :keyWord="'upstreamDownstreamManagement'"
            :routeName="$route.name"
            @getStaff="toGetStaffList"
            :transmitStr="'转发后的招聘信息'"
            :needStaff="true"
            :type="whichType - 1"
          ></job-item-for-recruit>
        </div>
        <van-empty v-else description="暂无数据" />
      </van-tab>
      <van-tab title="员工信息" v-if="Object.keys(selectedJobObj).length > 0">
        <div v-if="staffList.length">
          <van-divider v-if="whichType != 2" :style="{color: '#1989fa', borderColor: '#1989fa', padding: '0 66px'}">
            当前查看的职位
          </van-divider>
          <job-item-for-recruit
            :key="selectedJobObj.id"
            :jobItem="selectedJobObj"
            :keyWord="'upstreamDownstreamManagement'"
            :routeName="$route.name"
            @getStaff="toGetStaffList"
            :transmitStr="'转发后的招聘信息'"
            :needStaff="true"
            :type="whichType - 1"
          ></job-item-for-recruit>
          <van-divider :style="{color: '#1989fa', borderColor: '#1989fa', padding: '0 66px'}">
            该招聘信息下全部员工的信息
          </van-divider>
          <com-multiple-checkbox-card
            ref="comMultipleCheckboxCard"
            :dataList="staffList"
            :actionType="'add'"
            :type="whichType"
            :selectedSharedJobId="selectedJobObj.id"
            :keyWord="'upDownCooperationFee'"
            @sendSelectedArr="sendSelectedArr($event)"
          ></com-multiple-checkbox-card>
        </div>
        <van-empty v-else description="暂无数据" />
      </van-tab>
    </van-tabs>
    <van-popup
      v-model="popUpShow"
      class="popupDiv"
      closeable
      close-icon="close"
      position="bottom"
      :style="{height: '88%'}"
    >
      <div class="title" style="border-bottom: 1px solid #eee; ">
        支付合作费
      </div>
      <div class="popupContext" v-if="currentSelectedAplist.length">
        <van-cell class="checkbox_item" v-for="item in currentSelectedAplist" :key="item.job_user_id">
          <div style="display:flex; align-items: center;">
            <div>
              <van-image round cover width="1.2rem" height="1.2rem" :src="item.avatar ? item.avatar : logoImg" />
            </div>
            <div style="margin-left: 6px;">
              <div>姓名：{{ item.real_name }}</div>
              <div>
                合作费：<span style="color: red">{{ item.cooperation_money }}</span
                >元
              </div>
            </div>
          </div>
        </van-cell>
      </div>
      <van-row class="bottom" type="flex" justify="space-between" style="border-top: 1px solid #eee; padding: 10px 0;">
        <van-col span="16" style="padding-left: 20px">
          <div style="font-size:18px; margin-top:3px">
            合计：<span style="font-weight: bold; color: red; font-size:19px; margin-right: 5px;">{{ totalMoney }}</span
            >元
          </div>
        </van-col>
        <van-col span="6" style="padding-left: 20px">
          <van-button style="margin-right: 15px;" size="small" :type="'info'" @click="goPay">去支付 </van-button>
        </van-col>
      </van-row>
    </van-popup>

    <van-popup
      v-model="popupForm"
      safe-area-inset-bottom
      :close-on-click-overlay="false"
      closeable
      position="center"
      @click-overlay="onClickOverlay"
      :style="{width: '90%'}"
    >
      <div class="review_form">
        <van-nav-bar title="开始支付" />
        <van-form @submit="onSubmitReview" ref="review_form">
          <van-field
            autocomplete="off"
            v-model="payPwd"
            name="payPwd"
            label="支付密码"
            type="password"
            placeholder="请输入支付密码"
            required
            :rules="[{required: true, message: '请填写支付密码'}]"
          />
          <van-row style="margin: 16px;" type="flex" justify="space-between">
            <van-col span="11">
              <van-button round block type="warning" native-type="button" @click.stop="onClickOverlay">取消</van-button>
            </van-col>
            <van-col span="11">
              <van-button round block type="info" native-type="submit">提交</van-button>
            </van-col>
          </van-row>
        </van-form>
      </div>
    </van-popup>
  </div>
</template>

<script>
import comMyAttention from '../../../../components/comMyAttention'
import jobItemForRecruit from '../../recruitmentManagement/common/jobItemForRecruit'
import comMultipleCheckboxCard from '../../companyHome/common/comMultipleCheckboxCard'

import {Dialog, Toast} from 'vant'

export default {
  name: 'attentionPro',
  // whichType: 2为收到的合作费，3为支付的合作费。
  props: ['companyListData', 'whichType', 'job_id'],
  components: {
    comMyAttention,
    jobItemForRecruit,
    comMultipleCheckboxCard
  },
  data() {
    return {
      logoImg: 'https://jinpin-1304985105.cos.ap-guangzhou.myqcloud.com/image/defaultimage.jpg',
      activeTabIndex: 0,
      // 选中的公司
      selectedCompanyObj: {},
      needJobsList: [],
      // 选中的职位
      selectedJobObj: {},
      // 某公司下某个职位的选中的员工
      staffList: [],
      selectedStaffArr: [],

      popUpShow: false,
      // 当前的选中项
      currentSelectedAplist: [],
      totalMoney: 0,

      popupForm: false,
      isShowReview: false,
      payPwd: ''
    }
  },

  mounted() {
    // 使用bus总线。
    this.$bus.$on('getWorkload', workloadParam => {
      console.log('使用bus总线---接收传递的参数', workloadParam)
      // 三个参数缺一不可
      if (workloadParam.JobId && workloadParam.JobUserId && workloadParam.workDuration) {
        this.toSubmitWorkload(workloadParam)
      }
    })
  },

  methods: {
    async toViewShareJob(whichType, companyItem) {
      console.log('whichType操作的job_id为', whichType, companyItem)
      // 需要两个参数
      const paramShareObj = {
        job_id: this.job_id,
        // 下游公司的用户id
        apply_user_id: companyItem.apply_user_id
      }
      // whichType: 2为收到的合作费（收到上游的公司付款），3为支付的合作费（为下游公司付款）。
      const resp = await this.$api.job.cooperationHavedetail(paramShareObj)
      if (resp.code === 200) {
        // 获取需要上游公司的职位
        this.needJobsList = resp.data.jobinfo
        this.selectedCompanyObj = companyItem

        this.$nextTick(() => {
          this.activeTabIndex = 1
        })
      }
    },

    async toGetStaffList(jobItem) {
      if (jobItem.id) {
        // todo    job_id参数报错的问题
        console.log('点击某个的某个工作信息', JSON.stringify(jobItem))
        // 当前选中的职位
        this.selectedJobObj = jobItem
        const res = await this.$api.job.payDetailStaffList({job_id: jobItem.id})
        if (res.code === 200) {
          this.staffList = res.data.stafflist
          this.$nextTick(() => {
            this.activeTabIndex = 2
          })
        }
      } else {
        Toast('操作太快啦！为了您的账户安全，请点击左侧返回，重新进入该页面。')
      }
    },

    sendSelectedArr(data) {
      // 获取多选中的值
      console.log('父组件中---获取多选中---员工id组成的数组', data)
      this.selectedStaffArr = data
    },

    async toSubmitWorkload(param) {
      const result = await this.$api.job.submitWorkingDurationNum(param)
      if (result.code === 200) {
        Toast('工作时长，已提交成功！')
        this.toGetStaffList(this.selectedJobObj)
        // 取消选中项
        // this.$refs.comMultipleCheckboxCard.checkAllOrNot();
      }
    },

    _refreshData() {
      this.onClickOverlay()
      this.toGetStaffList(this.selectedJobObj)
      // 取消选中项
      this.$refs.comMultipleCheckboxCard.checkAllOrNot()
    },

    async onSubmitReview(val) {
      if (this.HasCaip < this.totalMoney * 1000) {
        Toast('您当前余额不足，请先充值！')
        return
      }

      const payParamObj = {
        jobUserIdList: this.jobUserIdList,
        payPassword: this.$Base64.encode(this.$md5(val.payPwd) + this.$md5('jinpin888'))
      }
      const res = await this.$api.job.toPayCooperationFee(payParamObj)
      if (res.code === 200) {
        let resCount = 0
        let success = 0
        let mes = ''
        for (let k in res.data) {
          resCount++
          //遍历对象，k即为key，obj[k]为当前k对应的值
          if (res.data[k].result === true) {
            success++
          } else {
            mes = res.data[k].data
          }
        }
        if (success === 0) {
          Toast.fail('支付失败,' + mes)
          return
        } else if (resCount === success) {
          Toast.success('支付成功')
          setTimeout(() => {
            this._refreshData()
          }, 500)
        } else if (resCount > success) {
          // Toast.success('部分代招费记录支付失败，请返回上一页重新勾选需要支付的代招费记录!')
          Dialog.alert({
            title: '部分合作费支付失败！',
            message: '部分合作费支付失败，请重新勾选需要支付的合作费!',
            theme: 'round-button',
            messageAlign: 'left'
          }).then(() => {
            this._refreshData()
          })
        }
      } else {
        Toast('操作失败请重试！')
      }
    },

    onClickOverlay() {
      this.popupForm = false
      this.payPwd = ''
      // 重置表单
      this.$refs.review_form.resetValidation()
    },

    async _getFinance() {
      // 校验余额是否够支付
      const res = await this.$api.job.getFinance()
      if (res.code === 200) {
        this.HasCaip = res.data.fina.caip || 0 // 余额，乘以1000
      }
    },

    goPay() {
      // Toast('去支付吧！');
      this.popupForm = true
      this.popUpShow = false
      this._getFinance()
    },

    toViewCooperationMoney() {
      if (!this.selectedStaffArr.length) {
        Toast('请至少选择一项')
        return null
      }

      let staffInfoList = []

      this.selectedStaffArr.forEach(sId => {
        const staffInfoObj = this.staffList.find(item => item.job_user_id === sId)
        staffInfoList.push(staffInfoObj)
      })

      // 需要进一步校验是否填写了工作时长
      if (!staffInfoList.every(info => info.cooperation_money && info.work_duration)) {
        Dialog.alert({
          title: '温馨提示',
          message:
            '有一部分员工的【工作时长】没有提交，请提交后再支付。若是下游合作费是按人收费的，请在输入框内输入1即可。',
          messageAlign: 'left'
        }).then(() => {
          // on close
        })
        return null
      }

      const moneySum = staffInfoList.reduce((pre, detailInfo) => pre + detailInfo.cooperation_money, 0)

      // 更新数据
      this.currentSelectedAplist = staffInfoList
      this.totalMoney = moneySum

      // 目前选择的参数。
      this.jobUserIdList = this.selectedStaffArr.map(eachId => ({
        jobUserId: eachId,
        jobId: this.selectedJobObj.id
      }))

      // console.log('支付的数据---参数', JSON.stringify(this.jobUserIdList));
      // console.log('支付的数据--员工数据--2', JSON.stringify(staffInfoList));

      this.$nextTick(() => {
        this.popUpShow = this.selectedStaffArr.length > 0
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.com_attentionPro {
  box-sizing: border-box;
  margin-bottom: 36px;
  .attentionPro {
    box-sizing: border-box;
    margin: 10px 0 16px 0;
    .step_desc {
      padding: 16px;
    }
  }

  /deep/.popupDiv {
    position: fixed;
    //border: 5px solid red;
    box-sizing: border-box;
    .van-cell {
      padding: 3px 16px;
    }
    .title {
      padding: 15px 0 0 0;
      text-align: center;
      font-size: 16px;
      height: 30px;
      position: absolute;
      //top: 0;
      z-index: 1;
      width: 100%;
    }
    .bottom {
      position: absolute;
      bottom: 1px;
      z-index: 9000;
      width: 100%;
      //border: 1px solid blue;
      box-sizing: border-box;
    }
    .popupContext {
      //border: 1px solid red;
      margin-top: 55px;
      //margin-bottom: 70px;
      max-height: 456px;
      overflow-y: scroll;
    }
  }
}
</style>
